﻿
Imports osi.interface.storage
Imports lock_t = lockWrapper(Of locks.eventCombLock)

Public Class locked_accessor_wrapper
    Inherits accessor_wrapper(Of accessor_t)
    Implements accessor_t

    Private ReadOnly l As lock_t = Nothing

    Public Sub New(ByVal a As accessor_t)
        MyBase.New(a)
        l = New lock_t()
    End Sub

    Private Function io(ByVal d As _do(Of eventComb)) As eventComb
        assert(Not d Is Nothing)
        Dim ec As eventComb = Nothing
        Return New eventComb(Function() As Boolean
                                 Return waitfor(l) AndAlso
                                        goto_next()
                             End Function,
                             Function() As Boolean
                                 ec = d()
                                 Return waitfor(ec) AndAlso
                                        goto_next()
                             End Function,
                             Function() As Boolean
                                 l.release()
                                 Return ec.end_result() AndAlso
                                        goto_end()
                             End Function)
    End Function

    Public Function read(ByVal key As String, ByVal result As pointer(Of bytes)) As eventComb _
                        Implements accessor_t.read
        Return io(Function() a.read(key, result))
    End Function

    Public Function write(ByVal key As String, ByVal value As bytes) As eventComb _
                         Implements accessor_t.write
        Return io(Function() a.write(key, value))
    End Function

    Public Function [erase](ByVal key As String) As eventComb _
                           Implements accessor_t.erase
        Return io(Function() a.erase(key))
    End Function

    Public Function exist(ByVal key As String, ByVal result As pointer(Of Boolean)) As eventComb _
                         Implements accessor_t.exist
        Return io(Function() a.exist(key, result))
    End Function

    Public Function sizeof(ByVal key As String, ByVal result As pointer(Of UInt64)) As eventComb _
                          Implements accessor_t.sizeof
        Return io(Function() a.sizeof(key, result))
    End Function
End Class
